import { TestConfig } from '../common/testConfig.js';

import {
    deleteEmployeeDataNetworkCache,
    getEmployeeData, updateOrCreateEmployeeData,
    getEmployeeDetailInfo,
    delEmployee, getRoleData, delRole,
    getRoleDetailInfo, updateOrCreateRoleData
} from '../../network/api.js';
import { TestSimulateData } from '../testMgr/testSimulateData.js';
import {
    getApiData, CommunicationPageData, ApiReturnStruct,
    DataPage, NetworkParser
} from '../../network/communicationConverter.js';
import { Engine } from '../engine.js';
import { Util } from '../../utils/util.js';
import { Definition } from '../common/definition.js';
import { FunctionPermissionDefinition } from '../platform/functionPermissionDefinition.js'
import { Employee, EmployeeMgrPageMode } from '../enterpriseMgt/employee.js';
import { EmployeeFilter } from '../enterpriseMgt/employeeFilter.js';
import { Role } from '../enterpriseMgt/role.js';
import { MessageUtil } from '@/utils/MessageUtil.js';


export class EnterpriseMgtUiAction {
    ///  获取员工数据
    async getEmployeeData(
        {
            orgId = null,  // 组织ID
            pageInfo = null,  // 分页信息 类型DataPage
            showLoadingPage = true,  // 是否显示加载页面
            filter = null,  // 过滤条件 类型 json
        }) {
        if (TestConfig.employeeDataTest) {

            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));

            let ret = new ApiReturnStruct();

            let communicationPageData = new CommunicationPageData();
            communicationPageData.pageInfo = pageInfo;
            communicationPageData.dataList = new TestSimulateData().simEmployeeData();

            ret.data = communicationPageData;
            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID 不在默认参数设置，避免TestConfig.warehouseTest 测试时，orgId为空
            let apiData = await getApiData(Employee.fromJson, orgId, pageInfo, getEmployeeData, filter, showLoadingPage);
            return apiData;
        }
    }

     /// 获取员工详情信息
    async getEmployeeDetailInfo(employeeId, orgId = null) {
        if (TestConfig.employeeDataTest) {
            // 模拟延时（例如：1000毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            let ret = new ApiReturnStruct();
            // In a real implementation, this would return actual employee data
            // For now, we'll return a mock response
            ret.data = new TestSimulateData().simEmployeeData()[0]; // Return first simulated employee
            return ret;
        } else {
            try {
                orgId = orgId ?? Engine.profile.org.orgId;
                let res = await getEmployeeDetailInfo(employeeId, orgId);
                
                // 解析数据
                const apiResult = NetworkParser.parseNetworkResult(res, Employee.fromJson);
                
                if (apiResult.data != null) {
                    return apiResult.data;
                } else {
                    if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                        MessageUtil.showErrorMsg(apiResult.resErr);
                    }
                    return null;
                }
            } catch (error) {
                console.error("获取员工详情失败:", error);
                MessageUtil.showErrorMsg("获取员工详情失败");
                return null;
            }
        }
    }

    /// 创建或更新员工信息
    async updateOrCreateEmployeeData(employee, orgId = null) {
        if (TestConfig.employeeDataTest) {
            // 模拟延时（例如：1000毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            let ret = new ApiReturnStruct();
            ret.data = employee;
            return ret;
        } else {
            try {
                orgId = orgId ?? Engine.profile.org.orgId;
                let res = await updateOrCreateEmployeeData({ employee: employee, orgId: orgId });
                
                // 解析数据
                const apiResult = NetworkParser.parseNetworkResult(res, null);
                
                if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                    return null;
                } else {
                    return apiResult;
                }
            } catch (error) {
                console.error("保存员工信息失败:", error);
                MessageUtil.showErrorMsg("保存员工信息失败");
                return null;
            }
        }
    }

    /// 删除员工
    async deleteEmployeeData(employeeId, orgId = null) {
        try {
            orgId = orgId ?? Engine.profile.org.orgId;
            let res = await delEmployee({ employeeId: employeeId, orgId: orgId });
            
            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, null);
            
            if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
                return null;
            } else {
                return apiResult;
            }
        } catch (error) {
            console.error("删除员工失败:", error);
            MessageUtil.showErrorMsg("删除员工失败");
            return null;
        }
    }


    /// 获取角色数据
    async getRoleData(
        {
            orgId = null,  // 组织ID
            pageInfo = null,  // 分页信息 类型DataPage
            showLoadingPage = true,  // 是否显示加载页面
            filter = null,  // 过滤条件 类型 json
        }) {
        if (TestConfig.roleDataTest) {
            // 模拟延时（例如：1000毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));

            let ret = new ApiReturnStruct();

            let communicationPageData = new CommunicationPageData();
            communicationPageData.pageInfo = pageInfo;
            communicationPageData.dataList = new TestSimulateData().simRoleData();

            ret.data = communicationPageData;
            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID
            let apiData = await getApiData(Role.fromJson, orgId, pageInfo, getRoleData, filter, showLoadingPage);
            return apiData;
        }
    }

    /// 获取角色详情
    async getRoleDetailInfo(roleId, orgId = null) {
        if (TestConfig.roleDataTest) {
            let ret = new ApiReturnStruct();
            ret.data = role;
            return ret;
        } else {
            let res = await getRoleDetailInfo(roleId, orgId ?? Engine.profile.org.orgId);
            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, Role.fromJsonAndInitWithOrgPermission);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /// 创建或是更新角色
    async updateOrCreateRoleData(role,orgId ) {
        if (TestConfig.roleDataTest) {
            let ret = new ApiReturnStruct();
            ret.data = role;
            return ret;
        } else {
            let res = await updateOrCreateRoleData({role:role,orgId:orgId??Engine.profile.org.orgId});
            // Assuming there's a parseNetworkResult function similar to the Employee version
            // If not, the raw data can be returned as is
            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, null);


            if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
                return null;
            }
            else {
                return apiResult;
            }
        }
    }

        /// 创建或是更新角色
    async deleteRoleData(id,orgId ) {
      
            let res = await delRole({roleId:id,orgId:orgId??Engine.profile.org.orgId});
            // Assuming there's a parseNetworkResult function similar to the Employee version
            // If not, the raw data can be returned as is
            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, null);


            if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
                return null;
            }
            else {
                return apiResult;
            }

        

    }

}